<?php
// +----------------------------------------------------------------------
// | B5Yii2CMF V3.0 [快捷通用基础管理开发平台]
// +----------------------------------------------------------------------
// | Author=>冰舞 <357145480@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace api\modules\admin\controllers\system;

use api\modules\admin\AuthController;
use api\utils\libs\CommonAction;
use common\models\system\DictData;
use common\services\system\DictService;

class DictDataController extends AuthController
{
    use CommonAction;

    protected string $model = DictData::class;
    protected bool $validate = true;

    /**
     * 获取某个字典数据列表
     * @return array
     */
    public function actionGetDataList(): array
    {
        $dictType = $this->request->get('type', '');
        return $this->success('', ['list' => DictService::selectDictDataByType($dictType)]);
    }

    protected function listBefore(array $params): array
    {
        $params['orderBy']['list_sort'] = 'asc';
        return $params;
    }

    protected function saveBefore(DictData $model, string $type, array $oldData = []): string
    {
        if (!in_array($type, ['add', 'edit'])) return '';
        if ($type == 'edit' && $model->type != $oldData['type']) return '字典类型发生改变';
        if ($type == 'add') {
            $typeInfo = DictService::selectTypeByType($model->type);
            if (!$typeInfo) return '字典类型信息不存在';
        }
        return '';
    }

    protected function saveAfter(DictData $model, string $type, array $oldData = []): void
    {
        // 默认保持唯一一个
        // if (in_array($type, ['add', 'edit'])) DictService::updateDataDefault($model);
    }
}
